package com.gcloud.googledrive;

import java.io.IOException;

import com.example.gcode.Archivos;
import com.example.gcode.GCloudSingleton;
import com.example.gcode.R;
import com.gcloud.dto.GCloudFile;
import com.gfilechooser.utils.FileUtils;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.utils.Constants;
import com.utils.GCloudUtil;

import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class DownloadGoogleFileActivity extends Activity {

	private ProgressDialog pDialog;

	public static Drive service;
	GoogleAccountCredential credential;
	private static final int REQUEST_ACCOUNT = 1;
	private static final int REQUEST_CODE = 100;
	private static String TAG = DownloadGoogleFileActivity.class
			.getSimpleName();
	private static String key_ = "";

	/* DROP BOX THINGS */

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.archivos_list);
		credential = GoogleAccountCredential.usingOAuth2(
				DownloadGoogleFileActivity.this, DriveScopes.DRIVE);
		DownloadGoogleFileActivity.key_ = getIntent().getStringExtra(
				Constants.FILE_KEY);
		startActivityForResult(credential.newChooseAccountIntent(),
				REQUEST_ACCOUNT);
	}

	private void showChooser() {
		// Use the GET_CONTENT intent from the utility class
		Intent target = FileUtils.createGetContentIntent();
		// Create the chooser Intent
		Intent intent = Intent.createChooser(target,
				getString(R.string.chooser_title));
		try {
			startActivityForResult(intent, REQUEST_CODE);
		} catch (ActivityNotFoundException e) {
			// The reason for the existence of aFileChooser
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_upload:

			Log.i("here", "upload");
			showChooser();
			break;
		case R.id.menu_download:
			Log.i("here", "download");
			break;
		case R.id.menu_delete:
			Log.i("here", "delete");
			break;
		case R.id.menu_bookmark:
			Log.i("here", "bookmark");
			break;
		case R.id.menu_save:
			Log.i("here", "save");
			break;
		case R.id.menu_search:
			Log.i("here", "search");
			break;
		case R.id.menu_google_drive:
			Log.i("here", "google drive");
			break;
		case R.id.menu_dropbox:
			Log.i("here", "dropbox");
			break;
		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.menu_layout, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_ACCOUNT:
			if (resultCode == RESULT_OK && data != null
					&& data.getExtras() != null) {
				String accountName = data
						.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
				credential.setSelectedAccountName(accountName);
				DownloadGoogleFileActivity.service = getDriveServices(credential);
				CargarArchivos downloadGoogleFile = new CargarArchivos();
				GCloudFile fileToDownload = GCloudUtil
						.getSelected(DownloadGoogleFileActivity.key_);
				if (fileToDownload != null
						&& fileToDownload.getAccount().equals(Constants.GOOGLE)) {
					downloadGoogleFile.setFile(
							GCloudUtil.gCloudFileToGoogleDrive(fileToDownload),
							DownloadGoogleFileActivity.service);
					downloadGoogleFile.execute();
				}
				Log.i("OnActivitty", "after execute");

			}
			break;		
		}
	}

	private Drive getDriveServices(GoogleAccountCredential credential) {
		return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
				new GsonFactory(), credential).build();
	}

	public void showToast(final String toast) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), toast,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	class CargarArchivos extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(DownloadGoogleFileActivity.this);
			 pDialog.setMessage("Downloading file to Google Drive ...");
			 pDialog.setIndeterminate(false);
			 pDialog.setCancelable(false);
			 pDialog.show();
		}

		Uri uri;
		GCloudSingleton gCloudSingleton;
		String answer = "false";
		Drive gService;
		File file;

		protected void setFile(File file, Drive service) {
			this.file = file;
			this.gService = service;
		}

		/**
		 * getting Inbox JSON
		 * */
		protected String doInBackground(String... voids) {

			Log.i("GCLOUD", "Ya entre a doInBackground :)");
			String methodName = "doInBackground()";
			Log.i(TAG, methodName);
			if (file.getDownloadUrl() != null
					&& file.getDownloadUrl().length() > 0) {
				try {
					HttpResponse resp = DownloadGoogleFileActivity.service
							.getRequestFactory()
							.buildGetRequest(
									new GenericUrl(file.getDownloadUrl()))
							.execute();
					Log.i(TAG, "Everything goes well");
					//TODO flush here
				} catch (IOException e) {
					Log.e(TAG, "IOException downloading: " + e);
					return "false";
				}
			} else {
				Log.i(TAG, "Is not a download file getDownloadUrl() = null");
				return "false";
			}
			return "true";
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			if (file_url.equalsIgnoreCase("true")) {
				showToast("everything well done");
				Intent newIntent = new Intent(DownloadGoogleFileActivity.this,
						Archivos.class);
				startActivity(newIntent);
			} else {
				showToast(answer);
			}

			// if(){
			// startActivityForResult(credential.newChooseAccountIntent(),
			// REQUEST_ACCOUNT);
			// }
			// updating UI from Background Thread
		}

	}

}